#include "head.h"


// 响应
int TLVResponse(int sockfd, char *buf, int type){
    train_t train;
    bzero(&train, sizeof(train));
    
    train.type = type;
    if(buf == NULL){
        train.len = 0;
    }else{
        train.len = strlen(buf);
        memcpy(train.path, buf, train.len);
    }

    send(sockfd, &train, sizeof(int) * 3 + train.len, MSG_NOSIGNAL);
    return 0;
}

// 功能：文件传输时，向客户端响应一个长度
int TLVResponseLen(int sockfd, int len, int type){
    train_t train;
    bzero(&train, sizeof(train));

    train.type = type;
    train.len = len;

    send(sockfd, &train, sizeof(int) * 3, MSG_NOSIGNAL);
    return 0;
}


// 功能：获取指令                      
int getInstruction(int sockfd, train_t *train){
    bzero(train, sizeof(train_t));

    int ret = recv(sockfd, &train->type, sizeof(int), MSG_WAITALL);
    ret = recv(sockfd, train->args, sizeof(int), MSG_WAITALL);
    ret = recv(sockfd, &train->len , sizeof(int), MSG_WAITALL);
    ret = recv(sockfd, train->path, train->len, MSG_WAITALL);
    
    if(ret <=0){
        return ret;
    }

    return 1;
}

// 功能：获取TLV的前两个字段
int getTL(int sockfd, train_t *train){
    bzero(train, sizeof(train_t));

    recv(sockfd, &train->type, sizeof(int), MSG_WAITALL);
    recv(sockfd, train->args, sizeof(int), MSG_WAITALL);
    recv(sockfd, &train->len, sizeof(int), MSG_WAITALL);

    return 0;
}

// 建立TCP连接
int establishConnect(char *ip, char *port){
    
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    
    struct sockaddr_in saddr;
    saddr.sin_addr.s_addr = inet_addr(ip);
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(atoi(port));

    int flag = 1;
    int ret = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
    ERROR_CHECK(ret, -1, "opt");

    ret = bind(sockfd, (struct sockaddr *)&saddr, sizeof(saddr));
    ERROR_CHECK(ret, -1, "bind");
    
    listen(sockfd, 10);

    return sockfd;
}

int epollAdd(int efd, int monitorfd){
    
    struct epoll_event event;
    bzero(&event, sizeof(event));

    event.data.fd = monitorfd;
    event.events = EPOLLIN;

    epoll_ctl(efd, EPOLL_CTL_ADD, monitorfd, &event);

    return 0;

}

int epollDel(int efd, int delfd){
    epoll_ctl(efd, EPOLL_CTL_DEL, delfd, NULL);
    return 0;
}
